﻿var SiteMap = (function () {
    var api = {};
    var sitemap;

    var _tmplCache = {};
    var _parseTemplate = function (str, data) {
        var err = "";
        try {
            var func = _tmplCache[str];
            if (!func) {
                var strFunc =
                    "var p=[],print=function(){p.push.apply(p,arguments);};" +
                    "with(obj){p.push('" +
                    str.replace(/[\r\t\n]/g, " ")
                    .replace(/'(?=[^#]*#>)/g, "\t")
                    .split("'").join("\\'")
                    .split("\t").join("'")
                    .replace(/<#=(.+?)#>/g, "',$1,'")
                    .split("<#").join("');")
                    .split("#>").join("p.push('")
                    + "');}return p.join('');";
                func = new Function("obj", strFunc);
                _tmplCache[str] = func;
            }
            return func(data);
        } catch (e) { err = e.message; }
        return "< # ERROR: " + err + " # >";
    }

    api.render = function (tmplId) {
        var $tmpl = $('script#' + tmplId + '[type="text/template"]');
        var resultHtml = _parseTemplate($tmpl.html(), sitemap);
        $tmpl.before(resultHtml);
    }

    api.renderToCurrent = function (tmplId) {
        var toCurrent = new Array();

        var pn = decodeURI(window.location.pathname).toLowerCase();

        var flag = false;
        var _detchData = function (arr) {
            $(arr).each(function (i, d) {
                if (d.Childs && d.Childs.length > 0) {
                    _detchData(d.Childs);
                }
                else {
                    if (d.Location.toLowerCase() == pn ||
                        d.Location.toLowerCase() == pn + '/Index'.toLowerCase()) {
                        flag = true;
                    }
                }

                if (flag) {
                    toCurrent.splice(0, 0, d);
                    return false;
                }
            });
        }
        _detchData([sitemap]);

        var $tmpl = $('script#' + tmplId + '[type="text/template"]');
        var resultHtml = _parseTemplate($tmpl.html(), toCurrent);
        $tmpl.before(resultHtml);
    }

    api.load = function (rootPath) {
        $.ajax({
            dataType: "json",
            async: false,
            url: '/SiteMap/GetJson',
            data: { "name": "/" + rootPath },
            success: function (data) {
                sitemap = data;
            }
        });
        console.info(sitemap);
    }

    return api;
})();